<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <el-card shadow="never" class="filter-container">
      <el-form :inline="true" :model="filterForm" ref="filterFormRef">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="filterForm.departmentId" placeholder="请选择科室" clearable>
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医生">
          <el-select v-model="filterForm.doctorId" placeholder="请选择医生" clearable>
            <el-option
              v-for="item in doctorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">总就诊人次</div>
          <div class="stats-value">{{ statistics.totalVisits }}</div>
          <div class="stats-compare">
            <span>同比：</span>
            <span :class="statistics.yearCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.yearCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.yearCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">平均日就诊人次</div>
          <div class="stats-value">{{ statistics.avgDailyVisits }}</div>
          <div class="stats-compare">
            <span>环比：</span>
            <span :class="statistics.monthCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.monthCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.monthCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">新患者占比</div>
          <div class="stats-value">{{ statistics.newPatientRatio }}%</div>
          <div class="stats-compare">
            <span>同比：</span>
            <span :class="statistics.newPatientCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.newPatientCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.newPatientCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-title">复诊率</div>
          <div class="stats-value">{{ statistics.returnVisitRate }}%</div>
          <div class="stats-compare">
            <span>同比：</span>
            <span :class="statistics.returnVisitCompare >= 0 ? 'up' : 'down'">
              <el-icon v-if="statistics.returnVisitCompare >= 0"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
              {{ Math.abs(statistics.returnVisitCompare || 0).toFixed(2) }}%
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>就诊趋势分析</span>
              <div class="chart-tools">
                <el-radio-group v-model="trendType" size="small" @change="loadVisitTrend">
                  <el-radio-button label="daily">日</el-radio-button>
                  <el-radio-button label="weekly">周</el-radio-button>
                  <el-radio-button label="monthly">月</el-radio-button>
                </el-radio-group>
                <el-select v-model="trendDataType" size="small" @change="loadVisitTrend" style="margin-left: 10px;">
                  <el-option label="总量" value="total" />
                  <el-option label="新患/复诊" value="newReturn" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container" v-loading="trendChartLoading">
            <div ref="trendChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分布图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>患者年龄分布</span>
            </div>
          </template>
          <div class="chart-container" v-loading="ageChartLoading">
            <div ref="ageChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>患者性别分布</span>
            </div>
          </template>
          <div class="chart-container" v-loading="genderChartLoading">
            <div ref="genderChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 科室和医生就诊排行 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>科室就诊排行</span>
            </div>
          </template>
          <div class="chart-container" v-loading="deptChartLoading">
            <div ref="deptChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>医生就诊排行</span>
            </div>
          </template>
          <div class="chart-container" v-loading="doctorChartLoading">
            <div ref="doctorChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { statisticsAPI, departmentAPI, userAPI } from '@/utils/api'
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
])

// 筛选表单
const filterFormRef = ref(null)
const filterForm = reactive({
  dateRange: [],
  departmentId: '',
  doctorId: ''
})

// 下拉选项
const departmentOptions = ref([])
const doctorOptions = ref([])

// 图表参数
const trendType = ref('daily')
const trendDataType = ref('total')

// 图表引用
const trendChartRef = ref(null)
const ageChartRef = ref(null)
const genderChartRef = ref(null)
const deptChartRef = ref(null)
const doctorChartRef = ref(null)

// 图表实例
let trendChart = null
let ageChart = null
let genderChart = null
let deptChart = null
let doctorChart = null

// 加载状态
const trendChartLoading = ref(false)
const ageChartLoading = ref(false)
const genderChartLoading = ref(false)
const deptChartLoading = ref(false)
const doctorChartLoading = ref(false)

// 统计数据
const statistics = reactive({
  totalVisits: 0,
  avgDailyVisits: 0,
  newPatientRatio: 0,
  returnVisitRate: 0,
  yearCompare: 0,
  monthCompare: 0,
  newPatientCompare: 0,
  returnVisitCompare: 0
})

// 日期快捷选项
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 初始化日期范围为最近30天
const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  filterForm.dateRange = [formatDate(start), formatDate(end)]
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 搜索
const handleSearch = () => {
  fetchStatistics()
  loadVisitTrend()
  loadAgeDistribution()
  loadGenderDistribution()
  loadDepartmentRank()
  loadDoctorRank()
}

// 重置搜索
const resetSearch = () => {
  filterFormRef.value.resetFields()
  initDateRange()
  handleSearch()
}

// 获取统计概览数据
const fetchStatistics = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      doctorId: filterForm.doctorId,
      groupBy: 'summary'
    }
    
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        totalVisits: 1539,
        avgDailyVisits: 51.3,
        newPatientRatio: 38.5,
        returnVisitRate: 61.5,
        yearCompare: 15.7,
        monthCompare: 8.3,
        newPatientCompare: 12.6,
        returnVisitCompare: 6.9
      }
    }
    
    statistics.totalVisits = mockData.data.totalVisits || 0
    statistics.avgDailyVisits = mockData.data.avgDailyVisits || 0
    statistics.newPatientRatio = mockData.data.newPatientRatio || 0
    statistics.returnVisitRate = mockData.data.returnVisitRate || 0
    statistics.yearCompare = mockData.data.yearCompare || 0
    statistics.monthCompare = mockData.data.monthCompare || 0
    statistics.newPatientCompare = mockData.data.newPatientCompare || 0
    statistics.returnVisitCompare = mockData.data.returnVisitCompare || 0
  } catch (error) {
    console.error('获取统计概览数据失败', error)
  }
}

// 加载就诊趋势数据
const loadVisitTrend = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  trendChartLoading.value = true
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      doctorId: filterForm.doctorId,
      groupBy: trendType.value,
      dataType: trendDataType.value
    }
    
    // 生成模拟数据
    let dates = []
    let counts = []
    let newPatients = []
    let returnPatients = []
    
    if (trendType.value === 'daily') {
      // 生成30天的数据
      for (let i = 0; i < 30; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (29 - i))
        dates.push(formatDate(date))
        
        const count = Math.floor(Math.random() * 20) + 40
        const newCount = Math.floor(count * (0.3 + Math.random() * 0.2))
        counts.push(count)
        newPatients.push(newCount)
        returnPatients.push(count - newCount)
      }
    } else if (trendType.value === 'weekly') {
      // 生成12周的数据
      for (let i = 0; i < 12; i++) {
        const date = new Date()
        date.setDate(date.getDate() - (11 - i) * 7)
        dates.push(`第${i + 1}周`)
        
        const count = Math.floor(Math.random() * 100) + 250
        const newCount = Math.floor(count * (0.3 + Math.random() * 0.2))
        counts.push(count)
        newPatients.push(newCount)
        returnPatients.push(count - newCount)
      }
    } else {
      // 生成12个月的数据
      for (let i = 0; i < 12; i++) {
        const date = new Date()
        date.setMonth(date.getMonth() - (11 - i))
        const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
        dates.push(monthNames[date.getMonth()])
        
        const count = Math.floor(Math.random() * 300) + 800
        const newCount = Math.floor(count * (0.3 + Math.random() * 0.2))
        counts.push(count)
        newPatients.push(newCount)
        returnPatients.push(count - newCount)
      }
    }
    
    const mockData = {
      success: true,
      data: {
        dates: dates,
        counts: counts,
        newPatients: newPatients,
        returnPatients: returnPatients
      }
    }
    
    renderTrendChart(mockData.data)
  } catch (error) {
    console.error('获取就诊趋势数据失败', error)
  } finally {
    trendChartLoading.value = false
  }
}

// 渲染就诊趋势图
const renderTrendChart = (data) => {
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }
  
  const xData = data.dates || []
  
  let option = null
  
  if (trendDataType.value === 'total') {
    // 总量趋势图
    const yData = data.counts || []
    
    option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: xData.length > 10 ? 45 : 0
        }
      },
      yAxis: {
        type: 'value',
        name: '就诊人次'
      },
      series: [
        {
          name: '就诊人次',
          type: 'line',
          data: yData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(64,158,255,0.3)' },
                { offset: 1, color: 'rgba(64,158,255,0.1)' }
              ]
            }
          }
        }
      ]
    }
  } else {
    // 新患/复诊趋势图
    const newPatients = data.newPatients || []
    const returnPatients = data.returnPatients || []
    
    option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['新患者', '复诊患者']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: xData.length > 10 ? 45 : 0
        }
      },
      yAxis: {
        type: 'value',
        name: '就诊人次'
      },
      series: [
        {
          name: '新患者',
          type: 'line',
          stack: 'Total',
          data: newPatients,
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '复诊患者',
          type: 'line',
          stack: 'Total',
          data: returnPatients,
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    }
  }
  
  trendChart.setOption(option)
  window.addEventListener('resize', () => trendChart.resize())
}

// 加载年龄分布数据
const loadAgeDistribution = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  ageChartLoading.value = true
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      doctorId: filterForm.doctorId,
      groupBy: 'age'
    }
    
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        ageGroups: ['0-10岁', '11-20岁', '21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-70岁', '71岁以上'],
        counts: [120, 145, 210, 258, 301, 226, 184, 95]
      }
    }
    
    renderAgeChart(mockData.data)
  } catch (error) {
    console.error('获取年龄分布数据失败', error)
  } finally {
    ageChartLoading.value = false
  }
}

// 渲染年龄分布图
const renderAgeChart = (data) => {
  if (!ageChart) {
    ageChart = echarts.init(ageChartRef.value)
  }
  
  const ageGroups = data.ageGroups || []
  const counts = data.counts || []
  
  // 准备饼图数据
  const pieData = ageGroups.map((group, index) => ({
    name: group,
    value: counts[index]
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ageGroups
    },
    series: [
      {
        name: '年龄分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  ageChart.setOption(option)
  window.addEventListener('resize', () => ageChart.resize())
}

// 加载性别分布数据
const loadGenderDistribution = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  genderChartLoading.value = true
  try {
    const params = {
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      departmentId: filterForm.departmentId,
      doctorId: filterForm.doctorId,
      groupBy: 'gender'
    }
    
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        male: 856,
        female: 683
      }
    }
    
    renderGenderChart(mockData.data)
  } catch (error) {
    console.error('获取性别分布数据失败', error)
  } finally {
    genderChartLoading.value = false
  }
}

// 渲染性别分布图
const renderGenderChart = (data) => {
  if (!genderChart) {
    genderChart = echarts.init(genderChartRef.value)
  }
  
  const pieData = [
    { name: '男', value: data.male || 0 },
    { name: '女', value: data.female || 0 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['男', '女']
    },
    color: ['#409EFF', '#FF6B6B'],
    series: [
      {
        name: '性别分布',
        type: 'pie',
        radius: '60%',
        center: ['40%', '50%'],
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  genderChart.setOption(option)
  window.addEventListener('resize', () => genderChart.resize())
}

// 加载科室就诊排行数据
const loadDepartmentRank = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  deptChartLoading.value = true
  try {
    // 使用静态模拟数据
    const mockData = {
      success: true,
      data: {
        departments: [
          { departmentId: "D001", departmentName: "内科", appointmentCount: 125, medicalOrderCount: 350 },
          { departmentId: "D002", departmentName: "外科", appointmentCount: 98, medicalOrderCount: 280 },
          { departmentId: "D003", departmentName: "儿科", appointmentCount: 76, medicalOrderCount: 215 },
          { departmentId: "D004", departmentName: "妇产科", appointmentCount: 68, medicalOrderCount: 192 },
          { departmentId: "D005", departmentName: "骨科", appointmentCount: 56, medicalOrderCount: 168 },
          { departmentId: "D006", departmentName: "眼科", appointmentCount: 48, medicalOrderCount: 144 },
          { departmentId: "D007", departmentName: "口腔科", appointmentCount: 42, medicalOrderCount: 126 },
          { departmentId: "D008", departmentName: "皮肤科", appointmentCount: 38, medicalOrderCount: 115 }
        ],
        values: [125, 98, 76, 68, 56, 48, 42, 38]
      }
    }
    
    renderDeptChart(mockData.data)
  } catch (error) {
    console.error('获取科室就诊排行数据失败', error)
  } finally {
    deptChartLoading.value = false
  }
}

// 渲染科室排行图
const renderDeptChart = (data) => {
  if (!deptChart) {
    deptChart = echarts.init(deptChartRef.value)
  }
  
  // 处理科室数据
  const departments = data.departments || []
  
  // 确保每个科室都有正确的数据
  const processedDepts = departments.map(dept => {
    let deptName = dept.departmentName || '未知科室';
    let value = dept.appointmentCount || 0;
    
    return {
      department: deptName,
      value: value,
      id: dept.departmentId,
      orderCount: dept.medicalOrderCount || 0
    };
  });
  
  // 按数值排序
  const sortedData = processedDepts.sort((a, b) => b.value - a.value)
  
  // 取前10个科室
  const top10Data = sortedData.slice(0, 10)
  const deptNames = top10Data.map(item => item.department)
  const deptValues = top10Data.map(item => item.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const idx = params[0].dataIndex;
        const item = top10Data[idx];
        let tooltip = `${params[0].name}<br/>就诊人次: ${params[0].value}`;
        
        if (item) {
          if (item.orderCount) {
            tooltip += `<br/>医嘱数量: ${item.orderCount}`;
          }
          if (item.id) {
            tooltip += `<br/>科室ID: ${item.id}`;
          }
        }
        
        return tooltip;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '就诊人次'
    },
    yAxis: {
      type: 'category',
      data: deptNames,
      axisLabel: {
        interval: 0,
        formatter: (value) => {
          if (value && value.length > 8) {
            return value.substring(0, 8) + '...'
          }
          return value || '未知科室'
        }
      }
    },
    series: [
      {
        name: '就诊人次',
        type: 'bar',
        data: deptValues,
        itemStyle: {
          color: '#91CC75'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}人次'
        }
      }
    ]
  }
  
  deptChart.setOption(option)
  window.addEventListener('resize', () => deptChart.resize())
}

// 加载医生就诊排行数据
const loadDoctorRank = async () => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) return
  
  doctorChartLoading.value = true
  try {
    // 使用静态模拟数据替代API调用
    const mockData = {
      success: true,
      data: {
        doctors: [
          { doctorId: "001", doctorName: "李医生", departmentName: "内科", title: "副主任医师" },
          { doctorId: "002", doctorName: "王主任", departmentName: "内科", title: "主任医师" },
          { doctorId: "003", doctorName: "张医生", departmentName: "外科", title: "主治医师" },
          { doctorId: "004", doctorName: "刘医生", departmentName: "外科", title: "住院医师" },
          { doctorId: "005", doctorName: "陈医生", departmentName: "儿科", title: "主任医师" },
          { doctorId: "006", doctorName: null, departmentName: "妇产科", title: "副主任医师" },
          { doctorId: "007", doctorName: "杨医生", departmentName: "眼科", title: "主治医师" },
          { doctorId: "008", doctorName: "黄医生", departmentName: "口腔科", title: "住院医师" },
          { doctorId: "009", doctorName: "", departmentName: "皮肤科", title: "主治医师" },
          { doctorId: "010", doctorName: "吴医生", departmentName: "骨科", title: "主任医师" },
        ],
        values: [75, 68, 62, 58, 55, 50, 45, 40, 35, 30]
      }
    }
    
    renderDoctorChart(mockData.data)
  } catch (error) {
    console.error('获取医生就诊排行数据失败', error)
  } finally {
    doctorChartLoading.value = false
  }
}

// 渲染医生排行图
const renderDoctorChart = (data) => {
  if (!doctorChart) {
    doctorChart = echarts.init(doctorChartRef.value)
  }
  
  const doctors = data.doctors || []
  const values = data.values || []
  
  // 处理医生名称，包含处理doctorName为null的情况
  const processedDoctors = doctors.map((doctor, index) => {
    let displayName = '未命名医生';
    
    if (doctor.doctorName) {
      displayName = doctor.doctorName;
    } else if (doctor.title && doctor.departmentName) {
      displayName = `${doctor.departmentName}${doctor.title}`;
    } else if (doctor.departmentName) {
      displayName = `${doctor.departmentName}医生`;
    } else if (doctor.title) {
      displayName = doctor.title;
    } else if (doctor.doctorId) {
      displayName = `医生(${doctor.doctorId.substring(0, 6)})`;
    }
    
    return {
      doctor: displayName,
      value: values[index] || 0,
      department: doctor.departmentName || '未知科室',
      title: doctor.title || '未知职称',
      id: doctor.doctorId
    };
  });
  
  // 按数值排序
  const sortedData = processedDoctors.sort((a, b) => b.value - a.value)
  
  // 取前10个医生
  const top10Data = sortedData.slice(0, 10)
  const doctorNames = top10Data.map(item => item.doctor)
  const doctorValues = top10Data.map(item => item.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const idx = params[0].dataIndex;
        const item = top10Data[idx];
        let tooltip = `${params[0].name}<br/>就诊人次: ${params[0].value}`;
        
        if (item) {
          if (item.department) {
            tooltip += `<br/>科室: ${item.department}`;
          }
          if (item.title) {
            tooltip += `<br/>职称: ${item.title}`;
          }
          if (item.id) {
            tooltip += `<br/>ID: ${item.id}`;
          }
        }
        
        return tooltip;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '就诊人次'
    },
    yAxis: {
      type: 'category',
      data: doctorNames,
      axisLabel: {
        interval: 0,
        formatter: (value) => {
          if (value && value.length > 8) {
            return value.substring(0, 8) + '...'
          }
          return value || '未命名医生'
        }
      }
    },
    series: [
      {
        name: '就诊人次',
        type: 'bar',
        data: doctorValues,
        itemStyle: {
          color: '#5470C6'
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{c}人次'
        }
      }
    ]
  }
  
  doctorChart.setOption(option)
  window.addEventListener('resize', () => doctorChart.resize())
}

// 获取科室选项
const getDepartments = async () => {
  try {
    // 使用静态模拟数据
    departmentOptions.value = [
      { id: "D001", name: "内科" },
      { id: "D002", name: "外科" },
      { id: "D003", name: "儿科" },
      { id: "D004", name: "妇产科" },
      { id: "D005", name: "骨科" },
      { id: "D006", name: "眼科" },
      { id: "D007", name: "口腔科" },
      { id: "D008", name: "皮肤科" }
    ]
  } catch (error) {
    console.error('获取科室选项失败', error)
  }
}

// 获取医生选项
const getDoctors = async () => {
  try {
    // 使用静态模拟数据
    doctorOptions.value = [
      { id: "001", name: "李医生", departmentId: "D001" },
      { id: "002", name: "王主任", departmentId: "D001" },
      { id: "003", name: "张医生", departmentId: "D002" },
      { id: "004", name: "刘医生", departmentId: "D002" },
      { id: "005", name: "陈医生", departmentId: "D003" },
      { id: "006", name: "赵医生", departmentId: "D004" },
      { id: "007", name: "杨医生", departmentId: "D006" },
      { id: "008", name: "黄医生", departmentId: "D007" },
      { id: "009", name: "周医生", departmentId: "D008" },
      { id: "010", name: "吴医生", departmentId: "D005" }
    ]
  } catch (error) {
    console.error('获取医生选项失败', error)
  }
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    if (trendChartRef.value) {
      trendChart = echarts.init(trendChartRef.value)
    }
    if (ageChartRef.value) {
      ageChart = echarts.init(ageChartRef.value)
    }
    if (genderChartRef.value) {
      genderChart = echarts.init(genderChartRef.value)
    }
    if (deptChartRef.value) {
      deptChart = echarts.init(deptChartRef.value)
    }
    if (doctorChartRef.value) {
      doctorChart = echarts.init(doctorChartRef.value)
    }
  })
}

// 初始化数据
const initData = () => {
  initDateRange()
  getDepartments()
  getDoctors()
  fetchStatistics()
  loadVisitTrend()
  loadAgeDistribution()
  loadGenderDistribution()
  loadDepartmentRank()
  loadDoctorRank()
}

// 生命周期钩子
onMounted(() => {
  initCharts()
  initData()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 140px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.stats-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 15px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-compare {
  position: absolute;
  bottom: 15px;
  right: 20px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.stats-compare .up {
  color: #67C23A;
  margin-left: 5px;
}

.stats-compare .down {
  color: #F56C6C;
  margin-left: 5px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-tools {
  display: flex;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.chart {
  height: 100%;
  width: 100%;
}
</style> 